<?php

include_once "Model.php";
include_once "Artist.php";
include_once "Release.php";
include_once "Article.php";
include_once "User2Track.php";
include_once "Tags.php";
include_once "lib/WebServices/MusicBrainz.php";

class Track_ extends Model {
  private $mb; 
  
  public function Track_($attr=null){ 
  	
    $this->table_name = TRACK_TABLE; parent::__construct($attr);
    $this->mb = new MusicBrainz();
  }
  
  public function add(){
    $artist_name = $this->attributes['artist'];
    $mb_artist_id = $this->attributes['mb_artist_id'];
    $release_title = $this->attributes['release'];
    $mb_rel_id = $this->attributes['mb_rel_id'];
    $article_body = $this->attributes['article'];
    //delete the column that aren't in the mt_track table
    $this->attributes['artist'] = $this->attributes['mb_artist_id'] = 
    $this->attributes['article'] = $this->attributes['mb_rel_id'] = $this->attributes['release'] = null;
   
    //See if we have the artist
    $artist = new Artist_(array(mb_id=>$mb_artist_id));
    
    if($mb_artist_id != null && $artist->get()->id)
      $this->attributes['artist_id'] = $artist->id;
                                                                   
    else { //no? Add one then
      /*
      * we check if we have an exact match with our artist
      * names before inserting a new one to
      * keep duplication at a minimum
      */
      $artist->reset(array(name=>$artist_name));
      if($artist->get()->id)
        $this->attributes['artist_id'] = $artist->id;
      else{
        $artist->set(array(mb_id=>$mb_artist_id, time_added=>'NOW()'));
        $this->attributes['artist_id'] = $artist->add();
      }  
    }
    
    //See if we have the release
    if($mb_rel_id != null){
      $release = new Release_(array(mb_id=>$mb_rel_id));
      
      if($release->get()->id)
        $this->attributes[release_id] = $release->id;
      else { //no? Add one then
        /*
         * fetch the image from Last.fm (AudioScrobbler)
         */
        $this->mb->setMethod('release_img');
        try{
          $img_url = $this->mb->search($artist_name, $release_title)->getReleaseImg();
          if(stristr($img_url,'noimage/')) $img_url = null;	
        }
        catch(MTException $e){ 
          //TODO: or we could try another source
          $img_url = null;
        }
        /******************************************/
        $release->set(array(title=>$release_title,image=>$img_url,time_added=>'NOW()'));
        $this->attributes['release_id'] = $release->add();
      }
    }
    
    $this->attributes['time_added'] = 'NOW()';
    //this will return the newly created track id
    $this->id = parent::add();
    //add the track2user entry
    $user2track = new User2Track_(array(user_id=>Session::factory()->getUserId(),track_id=>$this->id));
    $user2track->add();
    /*
     * fetch the toptags for the track from Last.fm
     */
    try{
      $this->mb->setMethod('tags');
      $tags = $this->mb->search($artist_name, $this->attributes['title'])->getTags();
       
      if($tags){
        $theTags = new Tags_($tags);
        $theTags->add($this->id);
      }
    }catch(MTException $e){  }
    /******************************************/
    //add the corresponding article
    if($article_body){
      $article = new Article_(array(track_id=>$this->id, body=>$article_body));
      $article->add();
    }
      
    return $this->id;
  }
  
  public function getFull(){
  	$query = 'SELECT t.url,t.artist_id, t.rating,t.id,t.played_times, t.mb_id AS track_mb_id, t.mood, t.title, t.time_added, a.name,a.mb_id AS artist_mb_id,r.id AS release_id, r.title AS release_title, r.mb_id AS release_mb_id, r.image AS coverimage, user.id AS uid,user.name AS submitter,ar.body, COUNT(u2f.user_id) AS favs,u2f_.user_id AS fav_user
          FROM (mt_track t, mt_artist a, mt_user user)
          LEFT JOIN mt_release r ON (t.release_id = r.id) 
          LEFT JOIN mt_article ar ON (ar.track_id=t.id) 
          LEFT JOIN mt_user2fav u2f ON (t.id = u2f.track_id)
          LEFT JOIN mt_user2fav u2f_ ON (t.id = u2f_.track_id AND '.Session::factory()->getUserId().' = u2f_.user_id )
          WHERE t.id ='.$this->attributes['id'].'
          AND t.artist_id = a.id
          AND user.id = (
            SELECT user_id
            FROM mt_user2track
            WHERE track_id = t.id 
          )
          GROUP BY u2f.track_id';
    //echo $query;      
    return $this->SQL->query($query)->fetchObject();
  }
}

?>
